//
//  ContentViewController.m
//  ChengXinBao
//
//  Created by RongZhou on 17/2/13.
//  Copyright © 2017年 RongZhou. All rights reserved.
//

#import "ContentViewController.h"
#import "AddressBookController.h"
#import "MineViewController.h"
#import "FindViewController.h"
#import "DialPhoneViewController.h"
#import "XTYRandomKeyboard.h"
#import "LLKCollectionManage.h"
#import "CallModel.h"
#import "PPGetAddressBook.h"
#import <AFNetworking.h>
@interface ContentViewController ()<UITabBarControllerDelegate,UITabBarDelegate,dialPhoneNumberAndSave,UITextFieldDelegate>
@property(nonatomic,strong)UITextField *textField;
@property(nonatomic,strong)XTYRandomKeyboard *keyBoad;
@property(nonatomic,copy)NSString *phoneNumber;

@property(nonatomic,strong)NSMutableArray *addressArray;
@property(nonatomic,copy)NSString *addressName;
@property(nonatomic,copy)NSString *companyName;
@property(nonatomic,copy)NSString *phoneNumberArea;
@end

@implementation ContentViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self loadItemViewController];
    self.tabBarController.tabBar.delegate = self;
    self.delegate = self;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(resignFirstResponderAobiyt) name:@"shouldcloseTheBorad" object:nil];
    
}
-(void)resignFirstResponderAobiyt{
    [self.textField resignFirstResponder];
}
-(void)loadItemViewController{
    DialPhoneViewController *dialVc = [[DialPhoneViewController alloc] init];
    dialVc.phoneNumber = self.phoneNumber;
    [_textField addObserver:dialVc forKeyPath:@"text" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:NULL];
    UINavigationController *dialNav = [[UINavigationController alloc] initWithRootViewController:dialVc];
    AddressBookController *addressVc = [[AddressBookController alloc] init];
    UINavigationController *addressNav = [[UINavigationController alloc] initWithRootViewController:addressVc];
    FindViewController *findVc = [[FindViewController alloc] init];
    UINavigationController *findNav = [[UINavigationController alloc] initWithRootViewController:findVc];
    MineViewController *mineVc = [[MineViewController alloc] init];
    UINavigationController *mineNav = [[UINavigationController alloc] initWithRootViewController:mineVc];
    self.viewControllers = [NSArray arrayWithObjects:dialNav,addressNav,findNav,mineNav, nil];
    UITabBarItem *item0 = [self.tabBar.items objectAtIndex:0];
    item0.title = @"弹出";
    item0.image = [[UIImage imageNamed:@"menu_1"] imageWithRenderingMode: UIImageRenderingModeAlwaysOriginal];
    item0.selectedImage = [[UIImage imageNamed:@"call_menu_up"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    UITabBarItem *item1 = [self.tabBar.items objectAtIndex:1];
    item1.title = @"通讯录";
    item1.image = [[UIImage imageNamed:@"menu_2"] imageWithRenderingMode: UIImageRenderingModeAlwaysOriginal];
    item1.selectedImage = [[UIImage imageNamed:@"menu_2s"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    UITabBarItem *item2 = [self.tabBar.items objectAtIndex:2];
    item2.title = @"发现";
    item2.image = [[UIImage imageNamed:@"menu_4"] imageWithRenderingMode: UIImageRenderingModeAlwaysOriginal];
    item2.selectedImage = [[UIImage imageNamed:@"menu_4s"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    UITabBarItem *item3 = [self.tabBar.items objectAtIndex:3];
    item3.title = @"我";
    item3.image = [[UIImage imageNamed:@"menu_5"] imageWithRenderingMode: UIImageRenderingModeAlwaysOriginal];
    item3.selectedImage = [[UIImage imageNamed:@"menu_5s"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
}
-(void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController{
    UITabBarItem *item = [tabBarController.tabBar.items objectAtIndex:0];
    if (viewController == [tabBarController.viewControllers objectAtIndex:0]) {
        if (item == [self.tabBar.items objectAtIndex:0]) {
            if ([item.title  isEqual: @"弹出"]) {
                item.title = @"弹出";
                [self addCustomKeyBoard:viewController];
                [self.textField becomeFirstResponder];
                //                [self.textField resignFirstResponder];
            }else{
                item.title = @"弹出";
                [self addCustomKeyBoard:viewController];
                [self.textField resignFirstResponder];
                //                [self.textField becomeFirstResponder];
            }
            
        }else{
            [self addCustomKeyBoard:viewController];
            [self.textField resignFirstResponder];
        }
        
    }else{
        item.title = @"弹出";
        [self.textField resignFirstResponder];
    }

}
-(void)addCustomKeyBoard:(UIViewController *)viewController{
    self.textField = [[UITextField alloc] initWithFrame:CGRectZero];
    self.textField.backgroundColor = [UIColor clearColor];
    self.textField.delegate = self;
    self.keyBoad = [[XTYRandomKeyboard alloc] initWithTitleColor:[UIColor blackColor] backGroundImage:[UIImage imageNamed:@"bg.jpg"]];
    self.keyBoad.delegate = self;
   
    [_keyBoad setInputView:self.textField];
    [viewController.view addSubview:self.textField];
    
}
-(NSString *)dialPhoneNumberAndSavePhone:(NSString *)phoneNumber{
    NSLog(@"111=%@",phoneNumber);
    self.phoneNumber = phoneNumber;
   [self.textField resignFirstResponder];
    [self accordingPhoneNumberBackCompanyInfomation:phoneNumber];
    return phoneNumber;
    
}
-(NSString *)calueLocalDialPhoneNumberTime{
    NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    NSDate *date = [NSDate date];
    NSDateFormatter * df = [[NSDateFormatter alloc] init];
    df.dateFormat = @"YYYY年-MM月-dd日 HH:mm";
    [df setTimeZone:sourceTimeZone];//直接指定时区，北京时间
    return [df stringFromDate:date];
}
-(void)getAddressBookInformation:(NSString *)addressPhone{
    [PPGetAddressBook getOriginalAddressBook:^(NSArray<PPPersonModel *> *addressBookArray) {
        for (PPPersonModel *model in addressBookArray) {
            if (addressPhone == nil) {
                
            }else{
                if ([model.mobileArray indexOfObject:addressPhone] != NSNotFound) {
                    
                    _addressName = model.name;
                    NSLog(@"2%@",self.addressName);
                    break ;
                }else{
                    if (self.companyName) {
                        _addressName = self.companyName;
                        break;
                    }else{
                        _addressName = addressPhone;
                    }

                }
                
            }
        }
        if (self.phoneNumberArea == nil) {
            self.phoneNumberArea = @"";
        }
        CallModel *model = [[CallModel alloc] initWithUserName:self.addressName AndUserPhonenumber:addressPhone AndUserCallTime:[self calueLocalDialPhoneNumberTime] AndUserAddress:self.phoneNumberArea];
        NSLog(@"%@",model.userAddress);
        [[LLKCollectionManage shareManager] addCollect:model];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"backAndReloadData" object:nil];
    } authorizationFailure:^{
        
    }];
}
-(NSMutableArray *)addressArray{
    if (_addressArray == nil) {
        _addressArray = [[NSMutableArray alloc] init];
    }
    return _addressArray;
}
/**
 *  根据电话号码返回商家信息
 *
 *  @param phoneNumber 手机号
 *
 *  @return 商家名称
 */
-(void)accordingPhoneNumberBackCompanyInfomation:(NSString *)phoneNumber{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    dispatch_queue_t gloablQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_group_t groups = dispatch_group_create();
    dispatch_group_async(groups, gloablQueue, ^{
        NSString *str = ServiceUrl@"/customerApp/searchCustomerByPhone?phone=%@";
        NSString *url = [NSString stringWithFormat:str,phoneNumber];
        [manager GET:url parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
             NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
               self.companyName = dict[@"customerName"];
            dispatch_semaphore_signal(semaphore);
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            dispatch_semaphore_signal(semaphore);
        }];

    });
    dispatch_group_async(groups, gloablQueue, ^{
        NSString *str = ServiceUrl@"/phoneAreaApp/searchCustomerByPhone?phone=%@";
        NSString *url = [NSString stringWithFormat:str,phoneNumber];
        [manager GET:url parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
               self.phoneNumberArea = dict[@"area"];
            dispatch_semaphore_signal(semaphore);
          
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            dispatch_semaphore_signal(semaphore);
        }];

    });
    dispatch_group_notify(groups, gloablQueue, ^{
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        [self getAddressBookInformation:phoneNumber];
    });
}
/**
 *  获取手机号码归属地
 *
 *  @param phoneNumber
 */
-(void)checkPhoneNumberArea:(NSString *)phoneNumber{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSString *str = ServiceUrl@"/phoneAreaApp/searchCustomerByPhone?phone=%@";
    NSString *url = [NSString stringWithFormat:str,phoneNumber];
    [manager GET:url parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
    
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        self.phoneNumberArea = dict[@"area"];
        NSLog(@"%@",self.phoneNumberArea);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}
#pragma mark -检测文本输入情况
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
